<template>
  <div class="app-container">
    <el-card shadow="never">
      <div class="filter-container">
        <div style="float: right;">
          <el-radio-group v-model="viewMode" size="small">
            <el-radio-button value="card">
              <i class="el-icon-picture"></i> 卡片视图
            </el-radio-button>
            <el-radio-button value="list">
              <i class="el-icon-menu"></i> 列表视图
            </el-radio-button>
          </el-radio-group>
        </div>
      </div>
    </el-card>

    <div v-if="loading" class="loading-container">
      <i class="el-icon-loading"></i> 加载中...
    </div>

    <div v-if="error" class="error-message">
      <el-alert type="error" :closable="false">
        {{ error }}
      </el-alert>
    </div>

    <div v-if="!loading && !error && viewMode === 'card'" class="card-view">
      <el-row :gutter="20">
        <el-col
          v-for="classInfo in classList"
          :key="classInfo.id"
          :xs="24"
          :sm="12"
          :md="8"
          :lg="6"
          :xl="4"
        >
          <el-card class="class-card" shadow="hover">
            <template #header>
              <div class="clearfix">
                <span>{{ classInfo.className }}</span>
              </div>
            </template>
            <div class="class-info">
              <div class="info-item">
                <i class="el-icon-user"></i>
                <span>班级ID: {{ classInfo.id }}</span>
              </div>
              <div class="info-item">
                <i class="el-icon-time"></i>
                <span>创建时间: {{ formatTime(classInfo.createTime) }}</span>
              </div>
              <div class="action-buttons">
                <el-button
                  type="primary"
                  size="small"
                  @click="showClassCourses(classInfo)"
                >
                  查看课程
                </el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <div v-if="!loading && !error && viewMode === 'list'">
      <el-table
        :data="classList"
        border
        fit
        highlight-current-row
        style="width: 100%;"
      >
        <el-table-column label="班级ID" prop="id" align="center" width="80" />
        <el-table-column label="班级名称" prop="className" />
        <el-table-column label="学生人数" prop="studentCount" align="center" width="100" />
        <el-table-column label="创建时间" width="180">
          <template #default="{row}">
            {{ formatTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="120">
          <template #default="{row}">
            <el-button
              type="primary"
              size="small"
              @click="showClassCourses(row)"
            >
              查看课程
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog
      :title="currentClass.className + ' - 课程列表'"
      v-model="coursesDialogVisible"
      width="70%"
      :close-on-click-modal="false"
    >
      <div v-if="loading" class="dialog-loading">
        <i class="el-icon-loading"></i> 加载课程中...
      </div>
      <el-table
        v-else
        :data="classCourses"
        border
        fit
        highlight-current-row
        style="width: 100%;"
      >
        <el-table-column label="课程ID" prop="id" align="center" width="80" />
        <el-table-column label="课程名称" prop="courseName" />
        <el-table-column label="课程简介" prop="introduction" />
        <el-table-column label="操作" align="center" width="120">
          <template #default="{row}">
            <el-button
              type="success"
              size="small"
              :disabled="isCourseAdded(row.id)"
              @click="addToMyCourses(row.id)"
            >
              {{ isCourseAdded(row.id) ? '已添加' : '加入课程' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="coursesDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { studentApi } from '@/api/students'
import { useAuthStore } from '@/stores/auth'

export default {
  name: 'StudentClasses',
  setup() {
    const authStore = useAuthStore()
    const classList = ref([])
    const loading = ref(false)
    const error = ref(null)
    const viewMode = ref('card')
    const coursesDialogVisible = ref(false)
    const currentClass = ref({
      id: null,
      className: '',
      studentCount: 0,
      createTime: ''
    })
    const classCourses = ref([])
    const myCourses = ref([])

    const isCourseAdded = computed(() => (courseId) => {
      return myCourses.value.some(course => course.id === courseId)
    })

    const formatTime = (time) => {
      if (!time) return ''
      const date = new Date(time)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
      }).replace(/\//g, '-')
    }

    const fetchMyCourses = async (studentId) => {
      try {
        
        const response = await studentApi.getMyCourses(studentId)
        
        
        // 处理不同响应格式
        let courses = []
        if (Array.isArray(response)) {
          courses = response
        } else if (response && response.data) {
          courses = Array.isArray(response.data) ? response.data : [response.data]
        } else if (response && response.result) {
          courses = Array.isArray(response.result) ? response.result : [response.result]
        }
        
        myCourses.value = courses
        
      } catch (err) {
        console.error('[fetchMyCourses] 获取我的课程失败:', err)
        ElMessage.error('获取我的课程失败: ' + (err.message || '未知错误'))
      }
    }

    const fetchClasses = async () => {
      const userId = authStore.userId
      if (!userId) {
        error.value = '用户未登录'
        return
      }

      try {
        loading.value = true
        error.value = null
        
        
        const studentIdResponse = await studentApi.getStudentIdByUserId(userId)
       
        
        const studentId = studentIdResponse?.data || studentIdResponse?.result || studentIdResponse
        
        
        if (!studentId) {
          throw new Error('未获取到有效学生ID')
        }

        
        const response = await studentApi.getStudentClasses(studentId)
        
        
        // 处理不同响应格式
        let classes = []
        if (Array.isArray(response)) {
          classes = response
        } else if (response && response.data) {
          classes = Array.isArray(response.data) ? response.data : [response.data]
        } else if (response && response.result) {
          classes = Array.isArray(response.result) ? response.result : [response.result]
        }
        
        classList.value = classes.map(item => ({
          id: item.classId || item.id,
          className: item.className,
          studentCount: item.studentCount || 0,
          createTime: item.createTime || ''
        }))
      

        await fetchMyCourses(studentId)
        
      } catch (err) {
        console.error('[fetchClasses] 获取班级列表失败:', err)
        error.value = '获取班级列表失败: ' + (err.response?.data?.message || err.message || '未知错误')
      } finally {
        loading.value = false
      }
    }

    const showClassCourses = async (classInfo) => {
      if (!classInfo?.id) {
        ElMessage.error('无效的班级信息')
        return
      }
      
      const userId = authStore.userId
      if (!userId) return
      
      try {
        loading.value = true
        currentClass.value = classInfo
        
        
        const studentIdResponse = await studentApi.getStudentIdByUserId(userId)
        
        const studentId = studentIdResponse?.data || studentIdResponse?.result || studentIdResponse
        
        
        const response = await studentApi.getClassCourses(studentId, classInfo.id)
        
        
        // 处理不同响应格式
        let courses = []
        if (Array.isArray(response)) {
          courses = response
        } else if (response && response.data) {
          courses = Array.isArray(response.data) ? response.data : [response.data]
        } else if (response && response.result) {
          courses = Array.isArray(response.result) ? response.result : [response.result]
        }
        
        classCourses.value = courses.map(course => ({
          id: course.id,
          courseName: course.courseName || '未命名课程',
          introduction: course.introduction || '暂无简介',
          joinTime: course.joinTime || new Date().toISOString()
        }))
        
        coursesDialogVisible.value = true
      } catch (err) {
        console.error('[showClassCourses] 获取班级课程失败:', err)
        ElMessage.error('获取班级课程失败: ' + (err.message || '未知错误'))
      } finally {
        loading.value = false
      }
    }

const addToMyCourses = async (courseId) => {
  try {
    await ElMessageBox.confirm('确定要加入此课程吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const userId = authStore.userId
    const studentIdResponse = await studentApi.getStudentIdByUserId(userId)
    const studentId = studentIdResponse?.data || studentIdResponse
    
    const loadingInstance = ElLoading.service({
      lock: true,
      text: '正在添加课程...',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    
    try {
      const response = await studentApi.addCourseToStudent(studentId, courseId)
      console.log('API完整响应:', response)
      
      // 安全检查响应数据
      const responseData = response.data || response
      
      // 检查是否是课程已存在的提示
      if (typeof responseData === 'string' && responseData.includes('该课程已存在于学生课程表中')) {
        ElMessage.warning(responseData)
        return
      }
      
      // 处理成功响应
      if (response.status === 200) {
        ElMessage.success(typeof responseData === 'string' ? responseData : '课程添加成功！')
        await fetchMyCourses(studentId)
      } else {
        throw new Error(typeof responseData === 'string' ? responseData : '添加课程失败')
      }
    } catch (err) {
      console.error('添加课程失败:', err)
      // 处理各种可能的错误情况
      const errorMsg = err.response?.data || 
                      err.message || 
                      '添加课程失败'
      if (errorMsg.includes('该课程已存在于学生课程表中')) {
        ElMessage.warning(errorMsg)
      } else {
        ElMessage.error(errorMsg)
      }
    } finally {
      loadingInstance.close()
    }
  } catch (err) {
    if (err !== 'cancel') {
      console.error('操作失败:', err)
    }
  }
}

    onMounted(async () => {
      console.log('[onMounted] 组件挂载，开始获取班级数据')
      await fetchClasses()
    })

    return {
      classList,
      loading,
      error,
      viewMode,
      coursesDialogVisible,
      currentClass,
      classCourses,
      showClassCourses,
      addToMyCourses,
      isCourseAdded,
      formatTime
    }
  }
}
</script>

<style scoped>
.filter-container {
  margin-bottom: 20px;
}

.loading-container, .dialog-loading {
  text-align: center;
  padding: 50px 0;
  font-size: 16px;
  color: #666;
}

.loading-container i, .dialog-loading i {
  margin-right: 10px;
  font-size: 20px;
}

.error-message {
  margin-bottom: 20px;
}

.card-view {
  margin-top: 20px;
}

.class-card {
  margin-bottom: 20px;
  transition: all 0.3s;
}

.class-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.1);
}

.class-info {
  margin-bottom: 10px;
}

.info-item {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}

.info-item i {
  margin-right: 8px;
  color: #409EFF;
}

.action-buttons {
  margin-top: 15px;
  text-align: center;
}

.clearfix::after {
  content: "";
  display: table;
  clear: both;
}
</style>